package com.shishuo.cms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.constant.ExceptionConstant;
import com.shishuo.cms.dao.GoldDao;
import com.shishuo.cms.entity.CashEntity;
import com.shishuo.cms.entity.GoldEntity;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.entity.vo.PageVo;

@Service
public class GoldService extends BaseService<GoldEntity, Long> {
	private GoldDao goldDao;

	@Autowired
	private UserService userService;
	@Autowired
	private CashService cashService;
	@Autowired
	public void setGoldDao(GoldDao goldDao) {
		super.setBaseDao(goldDao);
		this.goldDao = goldDao;
	}
	public PageVo<GoldEntity> getAllListPage(int pageNum,long userId) throws Exception {
		PageVo<GoldEntity> pageVo = new PageVo<GoldEntity>(pageNum);
		List<GoldEntity> list =goldDao.getAllList(pageNum,(long)10,userId);
		pageVo.setList(list);
		pageVo.setCount(goldDao.getAllListCount(userId));
		return pageVo;
	}
	/**
	 * 用户金币兑换
	 * @param id
	 * @param inputGold
	 * @throws Exception 
	 */
	@Transactional
	public void exchangeGold(long userId, double inputGold) throws Exception {
		UserEntity userEntityDbEntity=userService.getById(userId);
		if (userEntityDbEntity.getUserGold()<inputGold) {
			throw new Exception(ExceptionConstant.EXCHANGE_GOLD_ERROR);
		}
		double cashCount=inputGold/100;
		userService.addUserGold(userId, 0-inputGold);//减金币
		userService.addUserMoney(userId, cashCount);//加钱
		GoldEntity goldEntity=new GoldEntity();
		goldEntity.setStatus(1);//金币兑换成功
		goldEntity.setUserId(userId);
		goldEntity.setGoldCount(inputGold);
		goldEntity.setGoldMsg("金币兑换现金");
		goldEntity.setPassMsg("兑换成功");
		goldDao.add(goldEntity);
		CashEntity cashEntity =new CashEntity();
		cashEntity.setCashCount(cashCount);
		cashEntity.setStatus(1);
		cashEntity.setCashMsg("金币兑换");
		cashEntity.setPassUserId(1);
		cashEntity.setUserId(userId);
		cashEntity.setPassMsg("兑换成功");
		cashService.insert(cashEntity);
	}
}